package com.dc.datacollect.helpers;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * bean提供
 *
 * @author zhuangjie
 * @date 2023/06/23
 */
@Component
public class BeanProvide {

    @Autowired
    private BeanFactory beanFactory;

    /**
     * 根据类型返回，如果有多个，抛出异常
     * @param clazz
     * @return
     * @param <T>
     */
    public <T> T inject(Class<T> clazz) {
        return beanFactory.getBean(clazz);
    }

    /**
     * 从Bean容器中根据beanName获取，并如果是T实例就转为T返回，否则返回null
     * @param beanName
     * @param clazz
     * @return
     * @param <T>
     */
    public <T> T inject(String beanName, Class<T> clazz) {
        Object bean = beanFactory.getBean(beanName);
        if (clazz.isInstance(bean)) {
            return clazz.cast(bean);
        }
        return null;
    }
}
